<?php

namespace App\Http\Controllers;

use App\Models\Permission;
use App\Models\Role as Role;
use Illuminate\Http\Request;

class RolesController extends Controller
{
    //增
    public function store(Request $request)
    {
        $role = Role::create([
            'name' => $request->name,
            'guard_name' => 'api',
            'group' => $request->group,
            'description' => $request->description,
        ]);
        if($request->has('permissions')){
            $role->syncPermissions(Permission::whereIn('id', $request->input('permissions'))->get());
        }
        return $this->respondSuccess($role);
    }
    //删
    public function destroy(Role $role)
    {
        $data = $role->delete();
        return $this->respondSuccess($data);
    }

    //改
    public function update(Request $request, Role $role)
    {
        $data = $request->only(['name', 'group', 'description']);
        $data = $role->update($data);
        if($request->has('permissions')){
            $role->syncPermissions(Permission::whereIn('id', $request->input('permissions'))->get());
        }
        return $this->respondSuccess($role);

    }

    //查
    public function index(Request $request)
    {
        $users = Role::requestCriteria($request)->paginate($request->query('limit'));
        return $this->respondSuccess($users);
    }
    
    //详
    public function show(Role $role)
    {
        $role['permissions'] = $role->permissions()->get();
        return $this->respondSuccess($role);
    }
}
